// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

import {wxUtils} from "./wx/wxUtils";
import {gameUtils, sdkUtils} from "./utils";

cc.Class({
  extends: cc.Component,

  properties: {
    mixTime: 0.5,
    speedX: 0,

    runSpeed: 0,

    beginJumpSpeed: 0,
    collisionSpeed: 0,

    gameOverAudio: {
      default: null,
      url: cc.AudioClip
    },

  },

  // LIFE-CYCLE CALLBACKS:

  onLoad() {
    let body = this.body = this.node.getComponent(cc.RigidBody);
    body.enabledContactListener = true;

    var spine = this.spine = this.getComponent('sp.Skeleton');
    let self = this;
    self.spine.setCompleteListener((trackEntry, loopCount) => {
      var animationName = trackEntry.animation ? trackEntry.animation.name : "";
      // cc.log("[track %s][animation %s] complete: %s", trackEntry.trackIndex, animationName, loopCount);
      if (animationName === 'stand' || animationName === 'idle') {

        let num = self.GetRandomNum(1, 100);
        // cc.log("sddd num "+num);
        if (num < 30) {
          self.spine.setAnimation(0, "idle", false)
        } else {
          self.spine.setAnimation(0, "stand", false)
        }
        // this.spine.clearTrack(1);


      } else if (animationName === 'start') {
        self.spine.setAnimation(0, "run", false)
      } else if (animationName === 'run') {
        self.spine.setAnimation(0, "run", false)
      } else if (animationName === 'stop') {
        self.spine.setAnimation(0, "stand", false)
      } else if (animationName === 'jump_3') {
        self.spine.setAnimation(0, "stand", false)
      }
    });


    // this._setMix('jump_1', 'jump_2');
    // this._setMix('jump_2', 'jump_3');
    // this._setMix('jump_3', 'jump_1');
    // this._setMix('run', 'jump');

    this.state = 0;

    // this.speedX = 8;

    this.posy = this.node.y;
    this.isbejump = false;

  },

  // 获取最小值到最大值之前的整数随机数
  GetRandomNum: function (Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
  },

  start() {
    this.do_stand();
  },

  update(dt) {
    this.run_mb(dt);
  },

  _setMix(anim1, anim2) {
    this.spine.setMix(anim1, anim2, this.mixTime);
    this.spine.setMix(anim2, anim1, this.mixTime);
  },

  do_idle() {
    var oldAnim = this.spine.animation;
    if (oldAnim !== "idle") {
      this.spine.setAnimation(0, "idle", false)
    }
  },

  do_jump_1() {
    this.spine.setAnimation(0, "jump_1", false)
    this.spine.addAnimation(0, "jump_2", false)
  },

  do_jump_2() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "jump_2") {
      this.spine.setAnimation(0, "jump_2", true)
    }
  },

  do_jump_3() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "jump_3") {
      // cc.log("jump_2 ====================================== ");
      this.spine.setAnimation(0, "jump_3", false)
      setTimeout(() => {
        this.begin_jump();
      }, 200)
    }
  },

  do_run() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "run") {
      this.spine.setAnimation(0, "run", false)
    }
  },

  do_stand() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "stand" && oldAnim !== "idle") {
      this.spine.setAnimation(0, "stand", false)
    }
  },

  do_start() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "start" && oldAnim !== "run") {
      this.spine.setAnimation(0, "start", false)
    }
  },

  do_stop() {
    const oldAnim = this.spine.animation;
    if (oldAnim !== "stop" && oldAnim !== "stand" && oldAnim !== "idle") {
      this.spine.setAnimation(0, "stop", false)
    }
  },

  // 只在两个碰撞体开始接触时被调用一次
  onBeginContact: function (contact, selfCollider, otherCollider) {
    if (otherCollider.tag === 100) {
      if (this.state === 0) {

      } else if (this.state === 1 || this.state === 2) {
        if (this.isbejump) {
          this.gameOver();
        } else {
          this.state = 0;
          this.do_jump_3();
        }

      }
    } else {
      // cc.log("================onBeginContact==============222 "+otherCollider.tag);
      let isdie = otherCollider.getComponent("SmallBell").isdie()
      if (this.state === 1 && !isdie) {
        // 获取移动速度
        var velocity = this.body.linearVelocity;
        // cc.log("================onBeginContact==============333 "+this.collisionSpeed);
        this.body.linearVelocity = cc.v2(velocity.x, this.collisionSpeed);
        this.do_jump_1();

        this.isbejump = true;
      }


    }

  },

  gameOver: function () {
    this.state = 0;
    this.isbejump = false;

    cc.audioEngine.playEffect(this.gameOverAudio, false);

    window.Game.toPhbType = "js";
    // this.node.getParent().getComponent();
    wxUtils.showLoading({
      title: '加载中',
      mask: true
    });
    cc.director.loadScene("testScene", () => {
      wxUtils.postMessage({
        message: "getData",
        score: Game.GameOverScore,
        openid: sdkUtils.openId,
      });
      setTimeout(() => {
        wxUtils.hideLoading();
      }, 200)
    });
  },

  run_mb(dt) {
    if (this.pos) {

      let mx = this.pos.x - cc.winSize.width * 0.5;
      let x = this.node.x;

      if (x - mx < 0) {


        this.node.x += this.speedX * dt;
        if (this.node.x > mx) {
          this.node.x = mx;
          this.pos = null;
        }
        // this.node.setScaleX(1);
        if (0 === this.state) {
          this.do_start();
        }

      } else if (x - mx > 0) {

        this.node.x -= this.speedX * dt;
        if (this.node.x < mx) {
          this.node.x = mx;
          this.pos = null;
        }
        // this.node.setScaleX(-1);
        if (0 === this.state) {
          this.do_start();
        }
      } else {
        if (0 === this.state) {
          this.do_stop();
        }

      }
    }

    if (1 === this.state) {

    } else if (2 === this.state) {
      if (this.dieH - this.node.y > cc.winSize.height * 0.5) {
        this.gameOver();
      }
    }


  },

  die() {
    this.state = 2;
    this.dieH = this.node.y;
  },

  setDirection() {
    let mx = this.pos.x - cc.winSize.width * 0.5;
    let x = this.node.x;
    if (x - mx < -8) {
      this.node.setScaleX(1);

    } else if (x - mx > 8) {
      this.node.setScaleX(-1);
    }
  },

  touch_begin(event) {
    this.pos = cc.v2(event.touch.getLocation());
    this.setDirection();
  },


  touch_move(event) {
    this.pos = cc.v2(event.touch.getLocation());
    this.setDirection();
  },


  touch_end(event) {
    this.pos = cc.v2(event.touch.getLocation());
    if (0 === this.state) {
      //开始跳
      // this.state = 1;
      // this.begin_jump();
    }
  },

  begin_jump() {
    this.state = 1;
    this.body.linearVelocity = cc.v2(0, this.beginJumpSpeed);
    this.do_jump_1();
  },


  // 只在两个碰撞体结束接触时被调用一次
  onEndContact: function (contact, selfCollider, otherCollider) {
  },

  // 每次将要处理碰撞体接触逻辑时被调用
  onPreSolve: function (contact, selfCollider, otherCollider) {
    // cc.log("================onPreSolve==============");
  },

  // 每次处理完碰撞体接触逻辑时被调用
  onPostSolve: function (contact, selfCollider, otherCollider) {
    // cc.log("================onPostSolve==============");
  }

});
